package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 *获取用户信息
 * @Author xiqi
 *
 *
 *
 */
@Service
public class WechatServiceImpl implements WechatService {
    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.appSecret}")
    private String appSecret;
    /**
     * 获取用户的openId
     */
    @Override
    public String getOpenid(String code) {
        Map<String, Object> params = new HashMap<>();
        params.put("appid",appId);
        params.put("secret",appSecret);
        params.put("js_code",code);
        params.put("grant_type","authorization_code");
        String result = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session", params);
        if(StrUtil.isBlank(result)){
            throw  new BaseException("获取openId失败");
        }
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return jsonObject.getStr("openid");
    }

    private String getToken(){
        Map<String, Object> params = new HashMap<>();
        params.put("appid",appId);
        params.put("secret",appSecret);
        params.put("grant_type","client_credential");
        String s = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token ", params);
        if(StrUtil.isBlank(s)){
            throw  new BaseException("获取token失败");
        }
        JSONObject jsonObject = JSONUtil.parseObj(s);
        return jsonObject.getStr("access_token");
    }
    /**
     * 获取用户的手机号
     */
    @Override
    public String getPhoneNumber(String code) {
        Map<String, Object> params = new HashMap<>();
        params.put("code",code);
        String jsonStr = JSONUtil.toJsonStr(params);
        String s = HttpUtil.post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+this.getToken(),jsonStr);
        if(StrUtil.isBlank(s)){
            throw  new BaseException("获取手机号失败");
        }
        JSONObject jsonObject = JSONUtil.parseObj(s);
        String phoneInfo = jsonObject.getStr("phone_info");
        if(StrUtil.isBlank(phoneInfo)){
            throw  new BaseException("获取手机号失败");
        }

        JSONObject json = JSONUtil.parseObj(phoneInfo);
        return json.getStr("phoneNumber");
    }
}
